package com.util;

import com.model.Student;
import com.model.Teacher;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by guin_guo on 2015/10/27.
 */
public class XmlUtil {
    private static Document stuDocument;
    private static Document teacherDocument;
    private static Document courseDocument;
    private static Document curriDocument;

    /*private static final URL basePath = XmlUtil.class.getClassLoader().getResource("resource/");
    private static final URL stusXml = XmlUtil.class.getClassLoader().getResource("resource/students.xml");
    private static final URL teachersXml = XmlUtil.class.getClassLoader().getResource("resource/teachers.xml");
    private static final URL coursesXml = XmlUtil.class.getClassLoader().getResource("resource/courses.xml");
    private static final URL currilumssXml = XmlUtil.class.getClassLoader().getResource("resource/curriculum.xml");*/

    private static String basePath = System.getProperty("user.dir") + "\\resource\\";
    private static String stusXml = System.getProperty("user.dir") + "\\resource\\students.xml";
    private static String teachersXml = System.getProperty("user.dir") + "\\resource\\teachers.xml";
    private static String coursesXml = System.getProperty("user.dir") + "\\resource\\courses.xml";
    private static String currilumssXml = System.getProperty("user.dir") + "\\resource\\curriculum.xml";

    public static Document getStuDocument() {
        //如果stuDocument存在就返回
        if (stuDocument != null)
            return stuDocument;
        //不存在就创建一个
        try {
            SAXReader reader = new SAXReader();
            reader.setEncoding("UTF-8");
            stuDocument = reader.read(stusXml);
            return stuDocument;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Document getTeacherDocument() {
        if (teacherDocument != null) {
            return teacherDocument;
        }

        try {
            SAXReader reader = new SAXReader();
            reader.setEncoding("UTF-8");
            teacherDocument = reader.read(teachersXml);
            return teacherDocument;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Document getCourseDocument() {
        if (courseDocument != null) {
            return courseDocument;
        }

        try {
            SAXReader reader = new SAXReader();
            reader.setEncoding("UTF-8");
            courseDocument = reader.read(coursesXml);
            return courseDocument;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static Document getCurriDocument() {
        if (curriDocument != null) {
            return curriDocument;
        }

        try {
            SAXReader reader = new SAXReader();
            reader.setEncoding("UTF-8");
            curriDocument = reader.read(currilumssXml);
            return curriDocument;
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getStusXml() {
        return stusXml.toString();
    }

    public static String getTeachersXml() {
        return teachersXml.toString();
    }

    public static void write2XML(Document d,String name){
        XMLWriter out = null;
        try {
            String path = basePath+name;
            OutputFormat outFmt = new OutputFormat("\t", true);
            outFmt.setEncoding("UTF-8");
            out = new XMLWriter(new FileOutputStream(path), outFmt);
            out.write(d);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    public static Element SaveStudents(Element root, List<Student> students) {
        for (Student s : students) {
            Element es = root.addElement("student");
            es.addAttribute("id", s.getId() + "");
            es.addElement("account").addText(s.getAccount());
            es.addElement("name").addText(s.getName());
            es.addElement("sex").addText(s.getSex());
            es.addElement("age").addText(s.getAge());
            es.addElement("from").addText(s.getFrom());
            es.addElement("status").addText(s.getStatus());
            es.addElement("major").addText(s.getMajor());
            es.addElement("college").addText(s.getCollege());
            es.addElement("birth").addText(s.getBirth());
        }
        return root;
    }

    public static int getMaxId(Document d,String path) {
        //一组id的列表
        List<Element> eids = d.selectNodes(path);
        if(eids==null||eids.size()==0) {
            return 0;
        }
        List<Integer> ids = new ArrayList<Integer>();
        for(Element e:eids) {
            if(e==null||(e.attribute("id"))==null) continue;
            ids.add(Integer.parseInt(e.attribute("id").getValue()));
        }
        if(ids.size()<=0) return 0;
        Collections.sort(ids);
        return ids.get(ids.size()-1);
    }

    public static Element saveTeachers(Element root, List<Teacher> teachers) {
        for (Teacher teacher: teachers) {

        }
        return root;
    }
    /*  测试
        public static void main(String[] args) {
        XMLWriter out = null;
        try {
            Document d = DocumentHelper.createDocument();
            Element root = d.addElement("students");
            List<Student> l = new ArrayList<>(5);

            l.add(new Student(1,"20143008","桂楠","男","潮州","19950721","20","团员","网络工程3班","数学与信息学院"));
            l.add(new Student(1,"20143001","光伟","男","潮州","19950701","20","团员","网络工程3班","数学与信息学院"));
            l.add(new Student(1,"20143004","陈胤宗","男","潮州","19950921","20","团员","网络工程3班","数学与信息学院"));
            l.add(new Student(1,"20143007","邓子鹏","男","潮州","19950720","20","团员","网络工程3班","数学与信息学院"));
            l.add(new Student(1,"20143009","坚持","男","潮州","19950721","20","团员","网络工程3班","数学与信息学院"));

            root = SaveStudents(root,l);

            //创建XMLWriter来写数据
            try {
                out = new XMLWriter(new FileWriter(stusXml), OutputFormat.createPrettyPrint());
            } catch (IOException e) {
                e.printStackTrace();
            }
            //将节点写到xml文档中
            out.write(d);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(out!=null){
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }*/
}
